﻿using System;
using System.Linq;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using System.IO;

namespace SLSudoDB
{
    public class IsolatedStorageProvider : IFileStorageProvider
    {
        IsolatedStorageFile storage;
        public IsolatedStorageProvider()
        {
            storage = IsolatedStorageFile.GetUserStoreForApplication();
        }
        #region IFileStorageProvider Members

        public bool DirectoryExists(string path)
        {
            return storage.DirectoryExists(path);
        }

        public bool FileExists(string path)
        {
            return storage.FileExists(path);
        }

        public void CreateDirectory(string path)
        {
            storage.CreateDirectory(path);
        }

        public void DeleteFile(string path)
        {
            storage.DeleteFile(path);
        }

        public System.IO.StreamReader GetStreamReader(string path)
        {
            var stream = new IsolatedStorageFileStream(path, System.IO.FileMode.Open, storage);
            return new System.IO.StreamReader(stream);
        }

        public System.IO.StreamWriter GetStreamWriter(string path)
        {
            var stream = storage.OpenFile(path, FileMode.OpenOrCreate);// new IsolatedStorageFileStream(path, System.IO.FileMode.Open, storage);
            
            return new System.IO.StreamWriter(stream);
        }

        public string ReadAllText(string path)
        {
            string text;
            var stream = GetStreamReader(path);
            text = stream.ReadToEnd();
            //stream.BaseStream.Close();
            stream.Close();
            return text;
        }

        public void WriteAllText(string path, string text)
        {
            var stream = GetStreamWriter(path);
            stream.Write(text);
            //stream.BaseStream.Close();
            stream.Close();
        }

        public string[] GetFilesInDirectory(string path, string patteren)
        {
            return storage.GetFileNames(path + patteren);
            //var names = new List<string>();

            //files.ToList().ForEach(f => names.Add(new FileInfo(f).Name));
            //return names.ToArray();
        }

        #endregion
    }
}
